package nickthissen.iracing.common;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

import nickthissen.iracing.datamodels.Forum;
import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.datamodels.StringArrayResult;
import nickthissen.iracing.networking.Networking;

/**
 * Created by Nick on 20-5-13.
 */
public class ForumNames
{
    public static void load(Context context)
    {
        Log.i("ForumNames", "Start loading forum names.");
        Task<Void> t = new Task<Void>(context, loader);
        t.execute();
    }

    private static void setForumNames(ArrayList<String> forumNames)
    {
        try
                    {
                        Log.i("ForumNames", "Start setting forum names, nr found: " + forumNames.size());
                        for (String name : forumNames)
                        {
                            Log.i("ForumNames", "Received name: " + name);
                            String[] split = name.split(";");
                            if (split.length == 2)
                            {
                                int id = Integer.parseInt(split[0]);
                                Forum forum = ForumListManager.getInstance().forums.get(id);

                                if (forum != null)
                    {
                        forum.AbbreviatedName = split[1];
                        Log.i("ForumNames", "Set name: " + split[1]);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("ForumNames", "Error setting forum names: " + ex.getMessage());
        }
    }

    private static DataLoader<Void> loader = new DataLoader<Void>()
    {
        @Override
        public Result getData(Void in)
        {
            StringArrayResult result = Networking.getForumNames(this.getContext());
            if (result != null && result.Success)
            {
                return Result.ok(result.Object);
            }
            return Result.failed();
        }

        @Override
        public void onFinished(Result out)
        {
            if (out == null) out = Result.failed();
            if (out.Success)
            {
                setForumNames((ArrayList<String>)out.Object);
            }
            else
            {
                Log.i("ForumNames", "Failed loading forum names. " + out.DetailMessage);
            }
        }
    };
}
